package com.doordu.soa.service.web.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

/**
 * 数据库是int形式，并且以s秒来存储
 *
 */
@MappedTypes({Date.class})
@MappedJdbcTypes({JdbcType.INTEGER})
public class DateIntTypeHandler extends BaseTypeHandler<Date> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType)
			throws SQLException {
		Integer value = Long.valueOf(parameter.getTime() / 1000).intValue();
		ps.setInt(i, value);
	}

	@Override
	public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
		int i = rs.getInt(columnName);
		if (rs.wasNull()) {
			return null;
		}
		if (i == 0) {
			return null;
		}
		return new Date(i * 1000L);
	}

	@Override
	public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		int i = rs.getInt(columnIndex);
		if (rs.wasNull()) {
			return null;
		}
		if (i == 0) {
			return null;
		}
		return new Date(i * 1000L);
	}

	@Override
	public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		int i = cs.getInt(columnIndex);
		if (cs.wasNull()) {
			return null;
		}
		if (i == 0) {
			return null;
		}
		return  new Date(i * 1000L);
	}

}
